package com.yizisu.basemvvm.utils

/**
 * 若红楼梦空，亦初心不变
 * 作者：thinker
 * 包名：com.thinker.mvvm.util
 * 时间：2018/12/28 14:04
 * 描述：跳转Activity的工具类，可以实现一些动画
 */
import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.graphics.Point
import android.net.Uri
import android.os.Build
import android.os.Looper
import android.provider.Settings
import android.telephony.TelephonyManager
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.annotation.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import androidx.fragment.app.Fragment
import com.yizisu.basemvvm.*
import com.yizisu.basemvvm.mvvm.MvvmActivity
import kotlin.system.exitProcess

/**
 * 若红楼梦空，亦初心不变
 * 作者：weijiale
 * 包名：com.real.money.easy.utils
 * 时间：2018/7/23 17:
 * 描述：与Activity有关的工具类
 */
/**
 * activity跳转，普通跳转，默认动画
 *
 */
infix fun Context.navigateTo(cls: Class<*>) {
    val intent = Intent(this, cls)
    startActivity(intent)
}

inline fun Activity.navigateTo(cls: Class<*>, setParams: (Intent) -> Unit) {
    val intent = Intent(this, cls)
    setParams.invoke(intent)
    startActivity(intent)
}

/**
 * 携带view的动画，从一个界面飞入另一个
 */
fun Activity.navigateWithViews(cls: Class<*>, vararg viewName: Pair<View, String>) {
    val option = ActivityOptionsCompat.makeSceneTransitionAnimation(this, *viewName)
    ActivityCompat.startActivity(this, Intent(this, cls), option.toBundle())
}

inline fun Activity.navigateWithViews(
        cls: Class<*>,
        vararg viewName: Pair<View, String>,
        setParams: (Intent) -> Unit
) {
    val option = ActivityOptionsCompat.makeSceneTransitionAnimation(this, *viewName)
    val intent = Intent(this, cls)
    setParams.invoke(intent)
    ActivityCompat.startActivity(this, intent, option.toBundle())
}

/**
 * activity跳转，普通跳转，从某个按钮展开的动画
 */
fun Activity.navigateUpScale(view: View, cls: Class<*>) {
    val option = ActivityOptionsCompat.makeScaleUpAnimation(
            view,
            view.width / 2, view.height / 2, view.width, view.height
    )
    ActivityCompat.startActivity(this, Intent(this, cls), option.toBundle())
}

fun Activity.navigateClipReveal(view: View, cls: Class<*>) {
    val option = ActivityOptionsCompat.makeClipRevealAnimation(
            view,
            view.width / 2, view.height / 2, view.width, view.height
    )
    ActivityCompat.startActivity(this, Intent(this, cls), option.toBundle())
}

inline fun Activity.navigateUpScale(view: View, cls: Class<*>, setParams: (Intent) -> Unit) {
    val option = ActivityOptionsCompat.makeScaleUpAnimation(
            view,
            view.width / 2, view.height / 2, view.width, view.height
    )
    val intent = Intent(this, cls)
    setParams.invoke(intent)
    ActivityCompat.startActivity(this, intent, option.toBundle())
}

/**
 * 状态栏文字颜色，只有白色和黑色
 */
fun Activity.isStatusBarBlackTextColor(isDark: Boolean) {
    if (isDark) {
        //状态栏文字黑色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
    } else {
        //系统默认，状态栏文字白色
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE//白色
    }
}

/**
 * 透明状态栏
 */
fun AppCompatActivity.transparentStatusBar() {
    window.transparentStatusBar()
}

fun Window.transparentStatusBar() {
    val uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    statusBarColor = Color.TRANSPARENT
    decorView.systemUiVisibility = uiFlags
}

/**
 * 回到桌面，不退出app
 */
fun Activity.goHome() {
    val home = Intent(Intent.ACTION_MAIN)
    home.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
    home.addCategory(Intent.CATEGORY_HOME)
    startActivity(home)
}

/**
 * 跳转到浏览器
 */
fun Context.goToWeb(url: String) {
    try {
        val uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

/**
 * 系统分享
 */
fun Context.goToShare(title: String, text: String) {
    tryError {
        var shareIntent = Intent()
        shareIntent.action = Intent.ACTION_SEND
        shareIntent.type = "text/plain"
        shareIntent.putExtra(Intent.EXTRA_TEXT, text)
//切记需要使用Intent.createChooser，否则会出现别样的应用选择框，您可以试试
        shareIntent = Intent.createChooser(shareIntent, title)
        startActivity(shareIntent)
    }
}

/**
 * 打电话
 */
fun MvvmActivity.goCallPhone(number: String) {
    this.getPermission(kotlin.collections.mutableListOf(android.Manifest.permission.CALL_PHONE)) {
        if (it) {
            val intent = android.content.Intent(android.content.Intent.ACTION_CALL)
            val data = android.net.Uri.parse("tel:$number")
            intent.data = data
            startActivity(intent)
        } else {
            logE("打电话权限被拒绝")
        }
    }
}

/**
 * 获取设备的序列号
 * 需要ReadPhoneStatus权限
 */
@SuppressLint("MissingPermission", "HardwareIds")
fun getIMEI(context: Context): String {
    var imei: String? = null
    tryError {
        val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            telephonyManager.imei?.let {
                imei = it
            }
        } else {
            telephonyManager.deviceId?.let {
                imei = it
            }
        }
        if (imei == null) {
            imei = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
        }
    }
    return imei ?: "未获取到IMEI"
}

/**
 * 设置窗口的透明度
 */
fun Activity.setWindowAlpha(bgAlpha: Float) {
    window.setWindowAlpha(bgAlpha)
}

fun Window?.setWindowAlpha(bgAlpha: Float) {
    this ?: return
    val lp = attributes
    if (lp.alpha != bgAlpha) {
        lp.alpha = bgAlpha //0.0-1.0
        attributes = lp
    }
}

/**
 * 获取状态栏高度
 */
fun Resources.getStatusBarHeight(): Int {
    val resourceId = getIdentifier("status_bar_height", "dimen", "android");
    return getDimensionPixelOffset(resourceId)
}

/**
 * 获取导航栏高度
 */
fun Resources.getNavigationBarHeight(): Int {
    val resourceId = getIdentifier("navigation_bar_height", "dimen", "android");
    return getDimensionPixelSize(resourceId)
}

/**
 * 结束所有app
 */
fun Context.finishAllActivity(isForeClose: Boolean = true) {
    val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    am.appTasks?.forEach {
        it.finishAndRemoveTask()
    }
    if (isForeClose) {
        exitProcess(-1)
    }
}

/**
 * 代码运行在主线程
 */
fun Context.runOnUiThread(f: Context.() -> Unit) {
    if (isMainThread()) f() else mainHandler.post { f() }
}

/**
 * 是否是主线程
 */
fun isMainThread() = Looper.getMainLooper() === Looper.myLooper()

/**
 * toast
 */
fun CharSequence?.toast(duration: Int = Toast.LENGTH_SHORT, default: String? = "未知消息") {
    app.runOnUiThread {
        Toast.makeText(app, this@toast ?: default, duration).show()
    }
}

/**
 * toast
 * 这里只能是string中的资源文件
 */
fun Int?.toast(duration: Int = Toast.LENGTH_SHORT, default: String? = "未知消息") {
    var charSequence: CharSequence? = null
    if (this != null) {
        tryError {
            charSequence = getResString(this)
        }
    }
    charSequence.toast(duration, default)
}

/**
 * 隐藏键盘
 */
fun Activity?.hiddenKeyboard() {
    this ?: return
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    val focusView = window.decorView.findFocus()
    if (imm != null && focusView != null) {
        imm.hideSoftInputFromWindow(focusView.windowToken, 0)
    }
}

/**
 * 显示键盘
 */
fun Activity?.showKeyboard(focusView: View?) {
    this ?: return
    focusView ?: return
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    focusView.requestFocus()
    imm?.showSoftInput(focusView, 0)
}

/**
 * 添加fragment
 */
fun AppCompatActivity?.addFragment(@IdRes containerViewId: Int, @NonNull fragment: Fragment) {
    this?.apply {
        supportFragmentManager.beginTransaction()
                .add(containerViewId, fragment)
                .commitAllowingStateLoss()
    }
}

/**
 * 移除fragment
 */
fun AppCompatActivity?.removeFragment(@NonNull fragment: Fragment) {
    this?.apply {
        supportFragmentManager.beginTransaction()
                .remove(fragment)
                .commitAllowingStateLoss()
    }
}

/**
 * 添加fragment
 */
fun Fragment?.addFragment(@IdRes containerViewId: Int, @NonNull fragment: Fragment) {
    this?.apply {
        childFragmentManager.beginTransaction()
                .add(containerViewId, fragment)
                .commitAllowingStateLoss()
    }
}

/**
 * 移除fragment
 */
fun Fragment?.removeFragment(@NonNull fragment: Fragment) {
    this?.apply {
        childFragmentManager.beginTransaction()
                .remove(fragment)
                .commitAllowingStateLoss()
    }
}

/**
 * replace fragment
 */
fun AppCompatActivity?.replaceFragment(@IdRes containerViewId: Int, @NonNull fragment: Fragment) {
    this?.apply {
        supportFragmentManager.beginTransaction()
                .replace(containerViewId, fragment)
                .commitAllowingStateLoss()
    }
}


/**
 * replace fragment
 */
fun Fragment?.replaceFragment(@IdRes containerViewId: Int, @NonNull fragment: Fragment) {
    this?.apply {
        childFragmentManager.beginTransaction()
                .replace(containerViewId, fragment)
                .commitAllowingStateLoss()
    }
}

/**
 * 从哪个界面按的home，点击通知栏，进入哪个界面
 */
fun Context.getLastActivityIntent(): Intent {
    val appIntent = Intent()
    if (activityList.isNotEmpty()) {
        val topActivity = activityList[activityList.size - 1]
        appIntent.component = ComponentName(
                this.packageName,
                this.packageName + "." + topActivity.localClassName
        )
    }
    //关键的一步，设置启动模式
    appIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
    return appIntent
}

/**
 * 获取屏幕尺寸
 * isOnlyDisplay:true 不计算状态栏
 */
fun Activity.getScreenSize(isOnlyDisplay: Boolean = false): Point {
    val point = Point()
    if (isOnlyDisplay) {
        window.windowManager.defaultDisplay.getSize(point)
    } else {
        window.windowManager.defaultDisplay.getRealSize(point)
    }
    return point
}

/**
 * 获取屏幕尺寸
 * isOnlyDisplay:true 不计算状态栏
 */
fun View.getScreenSize(isOnlyDisplay: Boolean = false): Point {
    val point = Point()
    if (isOnlyDisplay) {
        this.display.getSize(point)
    } else {
        this.display.getRealSize(point)
    }
    return point
}

/**
 * 读取assets的文件
 */
fun Context.readAssetsFileToText(fileName: String?): String? {
    fileName ?: return null
    return try {
        val reader = assets.open(fileName).bufferedReader()
        val text = reader.readText()
        reader.close()
        text
    } catch (e: Throwable) {
        e.printStackTrace()
        null
    }
}

/**
 * 读取assets的文件
 * 转换为对象
 */
inline fun <reified T> Context.readAssetsFileFromJson(fileName: String?): T? {
    val text = readAssetsFileToText(fileName) ?: return null
    return try {
        gson.fromJson<T>(text, T::class.java)
    } catch (e: Throwable) {
        e.printStackTrace()
        null
    }
}

///**
// * 是否将value转换为字符串
// * 这里需要注意哪些value不是基本类型
// */
//fun Fragment?.put(key: String, value: Any?, isGson: Boolean = false) {
//    this?.apply {
//        val bundle = arguments ?: Bundle()
//
//    }
//}
//
//fun Bundle?.put(key: String, value: Any?, isGson: Boolean = false): Bundle {
//    val bundle = this ?: Bundle()
//    when (value) {
//        is Bundle? -> {
//            bundle.putBundle(key, value)
//        }
//        is IBinder? -> {
//            bundle.putBinder(key, value)
//        }
//        is Byte -> {
//            bundle.putByte(key, value)
//        }
//        is ByteArray? -> {
//            bundle.putByteArray(key, value)
//        }
//        is Char -> {
//            bundle.putChar(key, value)
//        }
//        is CharArray? -> {
//            bundle.putCharArray(key, value)
//        }
//        is CharSequence? -> {
//            bundle.putCharSequence(key, value)
//        }
//        is Float -> {
//            bundle.putFloat(key, value)
//        }
//        is FloatArray? -> {
//            bundle.putFloatArray(key, value)
//        }
//        is Int -> {
//            bundle.putInt(key, value)
//        }
//        is IntArray? -> {
//            bundle.putIntArray(key, value)
//        }
//        is Short -> {
//            bundle.putShort(key, value)
//        }
//        is ShortArray? -> {
//            bundle.putShortArray(key, value)
//        }
//        is Boolean -> {
//            bundle.putBoolean(key, value)
//        }
//        is BooleanArray? -> {
//            bundle.putBooleanArray(key, value)
//        }
//        is Double -> {
//            bundle.putDouble(key, value)
//        }
//        is DoubleArray? -> {
//            bundle.putDoubleArray(key, value)
//        }
//        is Long -> {
//            bundle.putLong(key, value)
//        }
//        is LongArray? -> {
//            bundle.putLongArray(key, value)
//        }
//        is Array<*>? -> {
//            bundle.putArray(key, value)
//        }
//        is ArrayList<*>? -> {
////            bundle.putList(key,value)
//        }
//    }
//    return bundle
//}
//
///**
// * 存放数组
// */
//fun Bundle.putArray(key: String, values: Array<*>?) {
//    if (values.isNullOrEmpty()) {
//        return
//    }
//    when (values[0]) {
//        is String? -> {
//            putStringArray(key,values as Array<out String?>)
//        }
//        else -> {
//        }
//    }
//}


